package com.task.platform.advice;


import com.task.platform.common.R;
import com.task.platform.exception.CustomException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors().forEach(error -> errors.put(error.getField(), error.getDefaultMessage()));
        return R.error(1, errors.toString());
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public R<String> handleUsernameNotFoundException(UsernameNotFoundException ex) {
        return R.error(ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public R<String> handleAllExceptions(Exception ex) {
        return R.error(ex.getMessage());
    }

    @ExceptionHandler(CustomException.class)
    public R<String> handleCustomExceptions(Exception ex) {
        return R.error(ex.getMessage());
    }
}
